package com.nercel.dsj.gksales.service.impl;

import com.google.gson.Gson;
import com.nercel.dsj.gksales.service.QiniuService;
import com.nercel.dsj.gksales.util.UploadResp;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;


@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class QiniuServiceImpl implements QiniuService {

	private static final String RETURN_BODY = 
			"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fname\":$(fname),"
					+ "\"fsize\":$(fsize),\"mimeType\":$(mimeType),\"uuid\":$(uuid)}";
	
    @Value("${qiniu.accessKey}")
    private String accessKey = "7lGNvl1N5t1PyfP5AfrWevPr1Cbtjyatanv5LCqu";

    
    @Value("${qiniu.secretKey}")
    private String secretKey = "SHyTP7bAyECrD0TfTqC8ewjZzmppC29fku6uikcR";
    
    @Value("${qiniu.defaultBucketName}")
    private String defaultBucketName;
    
	@Value("${upload.dir}")
	private String location;
	
	@Value("${qiniu.link}")
    private String qiniulink;
    
    
    public UploadResp put(String bucket, String key, File file){
    	Configuration cfg = new Configuration(Zone.zone0());
    	UploadManager uploadManager = new UploadManager(cfg);
    	StringMap putPolicy = new StringMap();
    	putPolicy.put("returnBody", RETURN_BODY);
	    Auth auth = Auth.create(accessKey, secretKey);
	    long expireSeconds = 3600;
	    String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
	    try {
	        Response response = uploadManager.put(file,key,upToken);
	        UploadResp putRet = new Gson().fromJson(response.bodyString(), UploadResp.class);
	        return putRet;
	    } catch (QiniuException ex) {
	    	ex.printStackTrace();
	        Response r = ex.response;
	        System.err.println(r.toString());
	        try {
	            System.err.println(r.bodyString());
	        } catch (QiniuException ex2) {
	        	ex2.printStackTrace();
	        }
	    }
	    return null;
    }
    
    /**
     * put to default bucket
     * @param key
     * @param file
     * @return
     */
    public UploadResp put(String key, File file){
		synchronized(this) {
			return put(defaultBucketName, key, file);
		}
    }
    
    public UploadResp upload(String key, MultipartFile multipartFile) throws IOException{
    	String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
		String extName = ""; // 扩展名格式：
		if (fileName.lastIndexOf(".") >= 0){
			extName = fileName.substring(fileName.lastIndexOf("."));
		}
		key = key + extName;
		Path rootLocation = Paths.get(this.location);
		if (!Files.exists(rootLocation)) {
			Files.createDirectories(rootLocation);
		}
		Path path = rootLocation.resolve(fileName);
		//本地保存
		Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
		//上传到七牛云
		UploadResp res = this.put(key, path.toFile());
    	return res;
    }
    
    public static void main(String[] args) {
    	QiniuServiceImpl xx = new QiniuServiceImpl();
    	xx.put("test", "test/index2.png", new File("d:/logo2.png"));
		System.out.println("abcdefg");
	}
    
	
}

